package com.engr.lyx.gateway.biz.config;

import com.engr.lyx.common.oauth2.AuthExceptionEntryPoint;
import com.engr.lyx.common.oauth2.CustomAccessDeniedHandler;
import com.engr.lyx.common.security.UserHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * @program: blog
 * @desc: 资源端 oauth2 配置
 * @author: lyx
 * @date: 2019-01-18 14:57
 **/
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class ResourceServiceConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private ResourceServerProperties properties;

    public static String[] ignoreUrls = {"/","/index", "/**/v2/api-docs/**", "/swagger-resources/**",
            "/swagger-ui.html", "/webjars/**", "/**/favicon.ico" };
    /**
     * 匿名用户
     */
    public static String[] anonymousUrls = {"/api/**"};


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint(new AuthExceptionEntryPoint())
                .accessDeniedHandler(new CustomAccessDeniedHandler())
                // 构建远程token,自定义用户信息转换器
                .tokenServices(UserHelper.buildRemoteTokenServices(properties));
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        //所有请求放行
        http.authorizeRequests().antMatchers(ignoreUrls).permitAll()
                .antMatchers(anonymousUrls).anonymous()
                .and().authorizeRequests()
                .antMatchers("/api/gateway/**").authenticated();
    }
}
